package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;
import java.util.Objects;

import static com.shanxia.codec.CodeConstant.ONEBYTE_ADDRS;
import static com.shanxia.codec.Decoder.*;

/**
 * C -> S
 * 充电桩参数整形设置/查询应答
 * 充电桩对后台服务器的充电桩整形参数设置报文应答
 */
@Data
public class Cmd2 extends ProtocolDataBase {

    public static final int MIN_SIZE = 43;

    private int v1;
    private int v2;
    private String sn;                        // 充电桩编码
    private int type;                         // 类型 [0-查询/ /1-设置]
    private int paramAddr;                    // 设置/查询参数起始地址
    private int paramNum;                     // 设置/查询个数
    private int code;                         // 设置/查询 结果
    private int data;                         // 设置数据 默认4个字节

    public Cmd2(){
        super.setCmd(2);
    }

    public static Cmd2 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd2 cmd = new Cmd2();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 1字节类型
        cmd.type = getUint8(dataField[offset++]);
        // 4字节设置/查询参数启始地址
        cmd.paramAddr = bytesToIntLittle(dataField, offset);
        offset += 4;
        // 1字节设置/查询个数
        cmd.paramNum = getUint8(dataField[offset++]);
        // 1字节设置/查询结果
        cmd.code = getUint8(dataField[offset++]);
        if (Objects.equals(cmd.type, 0)) {
            // N字节
            if (ONEBYTE_ADDRS.contains(cmd.paramAddr)) {
                cmd.data = getUint8(dataField[offset]);
            } else {
                cmd.data = bytesToIntLittle(dataField, offset);
            }
        }
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd2#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("充电桩编码:").append(sn).append("\n");
        buffer.append("类型 [0-查询/ /1-设置]:").append(type).append("\n");
        buffer.append("设置/查询参数起始地址:").append(paramAddr).append("\n");
        buffer.append("设置/查询个数:").append(paramNum).append("\n");
        buffer.append("设置/查询 结果:").append(code).append("\n");
        buffer.append("设置数据 默认4个字节:").append(data);
        return buffer.toString();
    }
}
